package com.aaa.controller;

import com.aaa.entity.WorkAttendance;
import com.aaa.entity.WorkAttendanceConfig;
import com.aaa.service.WorkAttendanceService;
import com.aaa.util.ThreadLocalUtil;
import com.aaa.entity.Result;
import com.aaa.entity.Users;
import com.aaa.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

import io.swagger.annotations.ApiOperation;

/**
 * 考勤管理相关的控制器类，负责处理与考勤相关的 HTTP 请求。
 * 该类通过调用业务逻辑层的服务，实现用户打卡等考勤操作。
 */
@RestController
@RequestMapping("/api/attendance")
public class WorkAttendanceController {

    @Autowired
    private WorkAttendanceService workAttendanceService;

    @Autowired
    private UserService userService;

    @Autowired
    private WorkAttendanceConfig workAttendanceConfig;

    private static final Logger logger = LoggerFactory.getLogger(WorkAttendanceController.class);

    @PostMapping("/checkIn")
    public ResponseEntity<Result<?>> checkIn(@RequestBody WorkAttendance workAttendance) {
        // 打印配置值以确认是否加载成功
        logger.info("公司位置配置 - 緯度: {}, 经度: {}, 有效打卡范围: {} 米",
                workAttendanceConfig.getCompanyLatitude(),
                workAttendanceConfig.getCompanyLongitude(),
                workAttendanceConfig.getInternalCheckRange());

        //记录打卡信息
        logger.info("进入checkIn方法");

        //根据token获取用户ID
        Map<String,Object> claims  = ThreadLocalUtil.get();
        if (claims == null || !claims.containsKey("id")) {
            logger.warn("无法从ThreadLocal获取用户信息或用户ID不存在");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Result.unauthorized("用户未登录或Token无效"));
        }
        String userId = claims.get("id").toString();
        logger.debug("从Token中获取用户ID: {}", userId);

        // 根据用户 ID 调用用户服务获取用户信息
        Users user = userService.getUserById(userId);
        // 检查用户信息是否存在
        if (user == null) {
            logger.warn("用户信息不存在，用户ID: {}", userId);
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(Result.notFound("用户信息不存在"));
        }
        logger.info("成功获取用户信息 - 用户ID: {}, 用户名: {}", userId, user.getName());

        // 调用考勤服务的打卡方法，传入用户 ID、用户名以及打卡相关信息
        Map<String, Object> result = workAttendanceService.checkIn(Long.parseLong(userId), user.getName(), workAttendance);
        // 从打卡结果中获取操作是否成功的标志
        Boolean success = (Boolean) result.get("success");

        // 根据操作是否成功进行不同的处理
        if (Boolean.TRUE.equals(success)) {
               return ResponseEntity.ok(Result.success(result));
        } else {
            String errorMsg = (String) result.get("message");
            return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED)
                    .body(Result.businessError(errorMsg));
        }
    }
}